import { useState, useCallback, useRef, useEffect } from 'react';
import { message } from 'antd';
import { ApiError, withRetry } from '../utils/request';

export interface AsyncState<T> {
    data: T | null;
    loading: boolean;
    error: ApiError | null;
    retryCount: number;
    lastUpdated?: Date;
    requestId?: string;
}

export interface UseAsyncOptions {
    immediate?: boolean; // 是否立即执行
    retryEnabled?: boolean; // 是否启用重试
    maxRetries?: number; // 最大重试次数
    retryDelay?: number; // 重试延迟
    showSuccessMessage?: boolean; // 是否显示成功消息
    successMessage?: string; // 成功消息
    onSuccess?: (data: any) => void; // 成功回调
    onError?: (error: ApiError) => void; // 错误回调
}

export function useAsync<T = any>(
    asyncFunction: () => Promise<T>,
    dependencies: any[] = [],
    options: UseAsyncOptions = {}
) {
    const {
        immediate = true,
        retryEnabled = true,
        maxRetries = 2,
        retryDelay = 1000,
        showSuccessMessage = false,
        successMessage = '操作成功',
        onSuccess,
        onError
    } = options;

    const [state, setState] = useState<AsyncState<T>>({
        data: null,
        loading: false,
        error: null,
        retryCount: 0,
        lastUpdated: undefined,
        requestId: undefined
    });

    const mountedRef = useRef(true);
    const abortControllerRef = useRef<AbortController | null>(null);

    useEffect(() => {
        mountedRef.current = true;
        return () => {
            mountedRef.current = false;
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
        };
    }, []);

    const execute = useCallback(async (retryCount = 0): Promise<T | null> => {
        if (!mountedRef.current) return null;

        // 生成请求ID用于跟踪
        const requestId = `req-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;

        // 取消之前的请求
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }
        
        // 创建新的 AbortController
        abortControllerRef.current = new AbortController();

        setState(prev => ({
            ...prev,
            loading: true,
            error: null,
            retryCount,
            requestId
        }));

        try {
            let result: T;

            if (retryEnabled) {
                result = await withRetry(asyncFunction, maxRetries, retryDelay);
            } else {
                result = await asyncFunction();
            }

            if (!mountedRef.current) return null;

            setState(prev => ({
                ...prev,
                data: result,
                loading: false,
                error: null,
                lastUpdated: new Date()
            }));

            if (showSuccessMessage && retryCount === 0) {
                message.success(successMessage);
            }

            onSuccess?.(result);
            return result;

        } catch (error) {
            if (!mountedRef.current) return null;

            const apiError = error as ApiError;
            
            setState(prev => ({
                ...prev,
                loading: false,
                error: apiError,
                retryCount
            }));

            onError?.(apiError);
            
            // 对于特定错误，不显示消息（由组件自己处理）
            if (apiError.status !== 504) {
                console.error('Async operation failed:', apiError);
            }

            return null;
        }
    }, [asyncFunction, retryEnabled, maxRetries, retryDelay, showSuccessMessage, successMessage, onSuccess, onError]);

    const retry = useCallback(() => {
        execute(state.retryCount + 1);
    }, [execute, state.retryCount]);

    const reset = useCallback(() => {
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }
        setState({
            data: null,
            loading: false,
            error: null,
            retryCount: 0,
            lastUpdated: undefined,
            requestId: undefined
        });
    }, []);

    const mutate = useCallback((newData: T | ((prevData: T | null) => T)) => {
        setState(prev => ({
            ...prev,
            data: typeof newData === 'function' 
                ? (newData as (prevData: T | null) => T)(prev.data)
                : newData
        }));
    }, []);

    // 自动执行
    useEffect(() => {
        if (immediate) {
            execute();
        }
    }, dependencies);

    return {
        ...state,
        execute,
        retry,
        reset,
        mutate,
        isRetryable: state.error?.retry || false
    };
}

// 专门用于数据获取的 hook
export function useFetch<T = any>(
    fetchFunction: () => Promise<T>,
    dependencies: any[] = [],
    options: UseAsyncOptions = {}
) {
    return useAsync(fetchFunction, dependencies, {
        immediate: true,
        retryEnabled: true,
        ...options
    });
}

// 专门用于表单提交的 hook
export function useSubmit<T = any>(
    submitFunction: () => Promise<T>,
    options: UseAsyncOptions = {}
) {
    return useAsync(submitFunction, [], {
        immediate: false,
        retryEnabled: false,
        showSuccessMessage: true,
        ...options
    });
}